// pages/FacialEdit/FacailEdit.js
var util = require('../../utils/util.js')
var PAGE_DATA = require('./pageData.js')
const app = getApp()
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		currentOperate: 0, // 当前进行的操作(人脸融合 || 人脸编辑)
		backwardUrl: false,	// 背景
		forwardUrl: false,	// API 调用返回的图片
		choosedPicture: false,
		fShowForwardImage: false,
		previewImageTagWidth: 0,
		previewImageTagHeight: 0,
		fConfirmPanel: false,
		attrOptionList: PAGE_DATA.attrOptionList,
		templateList: PAGE_DATA.templateList

	},
	
	backwardImageData: null, // 背景图 BASE64 数据
	backwardIGraymageData: null, //背景灰度图像 BASE64 数据
	forwardImageDataList: [], // 储存API 返回的图片, 避免重复的调用
	forwardImagTempUrl: undefined, //用于保存本地的临时url
	currentOption: null, // 当前选择的 前景类型
	urls: {
		editattr: "",
		merge:""
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function (options) {
		var self = this
		app.globalData.pages.FacialEdit = this
		this.device = app.globalData.myDevice
		//console.log(this.device)
		this.deviceRatio = this.device.windowWidth / 750

		// 请求百度API url
		if(app.globalData.token){
			this.urls.editattr = 'https://aip.baidubce.com/rest/2.0/face/v1/editattr?access_token=' + app.globalData.token
			this.urls.merge = 'https://aip.baidubce.com/rest/2.0/face/v1/merge?access_token=' + app.globalData.token
		}
	},

	/**
	 * 百度API初始化
	 */
	onInitBaiduApi(data){
		var token = data.token
		this.urls.editattr = 'https://aip.baidubce.com/rest/2.0/face/v1/editattr?access_token=' + token
		this.urls.merge = 'https://aip.baidubce.com/rest/2.0/face/v1/merge?access_token=' + token
	},

	//  属性编辑
	callBaiduApiAttrEdit: function (option) {
		var self = this
		var global = app.globalData
		
		var onLoading = true
		var MSG = function(msg, type, delay){
			if(!onLoading){
				return
			}
			var type = type || 'none'
			if(delay && delay > 0){
				setTimeout(()=>{
					wx.showToast({
						title: msg,
						icon: type,
						duration: 2000
					  })
				}, delay)
			}else{
				wx.showToast({
					title: msg,
					icon: type,
					duration: 3000
				  })
			}
		}

		wx.showLoading({
			title: '加载中',
			mask: true
		  })
		if (option.id == 4) {
			wx.request({
				url: 'https://aip.baidubce.com/rest/2.0/image-process/v1/selfie_anime',
				method: 'POST',
				data: {
					access_token: global.token,
					image: self.backwardImageData,
				},
				header: {
					'content-type': 'application/x-www-form-urlencoded' // 默认值
				},
				success: (res) => {
					var data = res.data
					if (typeof (data) != 'object') {
						try {
							data = JSON.parse(data)
						} catch (e) {
							console.log(e)
							data = false
							MSG('数据解析错误', 'none', 200)
						}
					}
					if (!data) {
						return
					}
					var imgData = data.image
					if (imgData) {
						option.forwardImageData = imgData
						if(onLoading){
							self.showForwardImage(true, option)
						}
					}else{
						MSG('错误:' + data.log_id, 'none', 200)
					}
				},
				fail: (res) => {
					console.log(res)
					MSG('发起请求失败', 'none', 200)
				},
				complete:() =>{
					if(onLoading){
						onLoading = false
						wx.hideLoading()
					}
				}
			})
		}
		else {
			const ACTION_TYPE = ['TO_KID', 'TO_OLD',  'TO_MALE', 'TO_FEMALE']
			wx.request({
				url: self.urls.editattr,
				method: 'POST',
				data: {
					image_type: 'BASE64',
					image: self.backwardImageData,
					action_type: ACTION_TYPE[option.id]
				},
				header: {
					'content-type': 'application/json' // 默认值
				},
				success: (res) => {
					var data = res.data
					// console.log(data)
					if (typeof (data) != 'object') {
						try {
							data = JSON.parse(data)
						} catch (e) {
							console.log(e)
							data = false
							MSG('数据解析错误', 'none', 200)
						}
					}
					if (!data) {
						return
					}
					var errorCode = data.error_code
					if (typeof(errorCode) == 'undefined') {
						MSG('请求错误', 'none', 200)
					} else if (errorCode > 0) {
						MSG(data.error_msg, 'none', 200)
						//console.log('调用错误:', data.error_msg)
					} else {
						var imgData = data.result.image
						if (imgData) {
							option.forwardImageData = imgData
							if(onLoading){
								self.showForwardImage(true, option)
							}
						}
					}

				},
				fail: (res) => {
					console.log(res)
					MSG('发起请求失败', 'none', 200)
				},
				complete:() =>{
					if(onLoading){
						wx.hideLoading()
						onLoading = false
					}
				}
			})
		}

		setTimeout(()=>{
			if(onLoading){
				wx.hideLoading()
				MSG('请求超时', 'none')
				onLoading = false
			}
		}, 5000)
	},
	// 融合
	callBaiduApiMerge: function (option) {
		var self = this
		var global = app.globalData
		
		var onLoading = true
		const MSG = function (msg, type, delay) {
			if(!onLoading){
				return
			}
		  var type = type || 'none'
		  if (delay && delay > 0) {
			setTimeout(() => {
			  wx.showToast({
				title: msg,
				icon: type,
				duration: 2000
			  })
			}, delay)
		  } else {
			wx.showToast({
			  title: msg,
			  icon: type,
			  duration: 3000
			})
		  }
		}
		option.imageData // TODE: 模板Base64获取
		self.backwardIGraymageData // TODE: 模板Base64获取
		wx.showLoading({
		  title: '加载中',
		  mask: true
		})
		wx.request({
		  url: self.urls.merge,
		  method: 'POST',
		  data: {
			//access_token: global.token,
			//image_type: 'BASE64',
			image_template: {
				image:option.backwardImageData, 
				image_type:'BASE64'
			},
			image_target: {
				image:self.backwardIGraymageData,
				image_type: 'BASE64'
			},
		  },
		  header: {
			'content-type': 'application/json' // 默认值
		  },
		  success: (res) => {
			var data = res.data
			// console.log(data)
			if (typeof (data) != 'object') {
			  try {
				data = JSON.parse(data)
			  } catch (e) {
				console.log(e)
				data = false
				MSG('数据解析错误', 'none', 200)
			  }
			}
			if (!data) {
			  return
			}
			var errorCode = data.error_code
			if (typeof (errorCode) == 'undefined') {
			  MSG('请求错误', 'none', 200)
			} else if (errorCode > 0) {
			  MSG(data.error_msg, 'none', 200)
			  console.log('调用错误:', data.error_msg)
			} else {
			  var imgData = data.result.merge_image
			  if (imgData) {
				option.forwardImageData = imgData
				if (onLoading) {
				  self.showForwardImage(true, option)
				}
			  }
			}
	
		  },
		  fail: (res) => {
			console.log(res)
			MSG('发起请求失败', 'none', 200)
		  },
		  complete: () => {
			  wx.hideLoading()
			  onLoading = false
		  }
		})
	
		setTimeout(() => {
		if(onLoading){
			wx.hideLoading()
		  MSG('请求超时', 'none')
		  onLoading = false
		}
		}, 5000)
		
	  },

	onChooseImage: function () {
		var self = this
		console.log('点击')
		// 打开系统相册
		wx.chooseImage({
			count: 5, // 默认9
			sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
			sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
			success: function (res) {
				console.log(res)
				var tempFilePath = res.tempFilePaths[0]
				console.log('选择的图像路劲:', tempFilePath)
				self.setData({
					backwardUrl: tempFilePath,
					choosedPicture: true,
					fConfirmPanel:true
				})
			},
			fail:res=>{
				console.log(res)
				wx.showToast({
					title: '选取失败',
					icon: 'none',
					duration: 3000
				  })
			},
			complete: function () {
				console.log('完成')
			}
		})

	},

	/**
	 * 格式化 前景图和背景图 Image 的大小
	 * @param {object} detail 
	 */
	formatImageTagSize(width, height){
		const MAX_WIDTH = 750
		const MAX_HEIGHT = 900

		width = width / this.deviceRatio
		height = height / this.deviceRatio
		// 限制宽高
		width = width > MAX_WIDTH ? MAX_WIDTH : width
		height = height > MAX_HEIGHT ? MAX_HEIGHT : height
		this.setData({
			previewImageTagWidth: width,
			previewImageTagHeight: height
		})
	},

	// 格式化灰度数据
	formatGrayData:function(){

	},

	/**
 * 背景图加载完毕
 * @param {object} event 
 */
	onBackwardImageLoad: function (event) {
		var self = this
		var width = event.detail.width
		var height = event.detail.height
		if(width < 256 || height < 256){
			console.log('图片尺寸太小了')
			this.setData({
				choosedPicture: false,
				backwardUrl: false
			})
			return
		}
		this.formatImageTagSize(width, height)

		// 转化问Base64
		self.backwardImageData = null
		self.backwardIGraymageData = null
		wx.getFileSystemManager().readFile({
			filePath: this.data.backwardUrl, //选择图片返回的相对路径
			encoding: 'base64', //编码格式
			success: res => { //成功的回调
				self.backwardImageData = res.data.toString()
				//console.log('Base64数据长度:', self.backwardImageData.length)
				// 显示顶部确认条
				self.setData({
					fConfirmPanel: true
				})

				// TODO: 灰度数据
				self.backwardIGraymageData = self.backwardImageData
			},
			fail: res => {
				console.log(res)
			}
		})

	},

	/**
	 * 用户切换选 前景效果
	 */
	onOptionChangeEvent: function (event) {
		var self = this
		var global = app.globalData
		if(!self.data.choosedPicture || self.backwardImageData == null){
			wx.showToast({
				title: '请先选择一张图片',
				icon: 'none',
				duration: 2000
			  })
			  return
		}

		if (!global.token) {
			console.log('无效的Token')
			return
		}
		//console.log(event)
		var operate = self.data.currentOperate
		var id  = parseInt(event.currentTarget.dataset.index) || 0
		// 分发
		switch(operate){
			case 1: // 表情融合
				var option = self.data.templateList[id]
				if (option == self.currentOption) {
					self.showForwardImage(false)
					return
				}
				self.onSelectTemplateItem(option)
				break;
			case 2:
				var option = self.data.attrOptionList[id]
				if (option == self.currentOption) {
					self.showForwardImage(false)
					return
				}
				self.onAttrChangeEvent(option)
				break;
		}
	},

	/**
	 * 用户 切换操作
	 */
	onOperateChangeEvent(event) {
		var self = this
		var id  = parseInt(event.currentTarget.dataset.index) || 0
		if(id <0){
			return
		}
		self.setData({
			currentOperate: id
		})
	},

	onAttrChangeEvent:function(option){
		var self = this
		if(option.forwardImageData){
			self.showForwardImage(true, option)
		}
		else{
			console.log("发起请求", option)
			self.callBaiduApiAttrEdit(option)
		}
	},

    onSelectTemplateItem: function (option) {
		var self = this
		if (option.forwardImageData) {
		self.showForwardImage(true, option)
		}
		else {
			// 读取模板 Base64数据
			if(!option.backwardImageData || option.backwardImageData == null){
				/* let data = util.loadBase64Image(option.url)
				if(data){
					option.backwardImageData = data
				}
				else{
					return
				} */
				return
		}
		console.log("发起请求", option)
			self.callBaiduApiMerge(option)
		}
  },

	

	/**
	 * 显示前景图像, API处理后的图像,并隐藏背景图像
	 * @param {boolean} show 
	 * @param {object} option 
	 */
	showForwardImage:function(show, option){
		var self = this
		if(self.currentOption != null){
			self.currentOption.selected = false
		}
		if(show){
			option.selected = true
			self.setData({
				fShowForwardImage: true,
				forwardUrl: option.forwardImageData || '',
			})
			self.currentOption = option
		}
		else{
			self.setData({
				fShowForwardImage: false,
			})
			self.currentOption = null
			self.forwardImagTempUrl = undefined
		}
		var operate = self.data.currentOperate
		if(operate == 1){
			self.setData({
				templateList: self.data.templateList
			})
		}
		else if(operate == 2){
			self.setData({
				attrOptionList: self.data.attrOptionList
			})
		}
	},

	/**
	 * 保存当前图片
	*/
	saveCurrentImage:function(){
		var self = this
		if(self.currentOption == null){
			return false
		}
		var id = self.currentOption.id
		if(self.forwardImageDataList[id] == null){
			return false
		}
		var res = util.saveBase64Image(self.forwardImageDataList[id], 'FacialEditTempImage' + id + '.png')
		if(res){
			self.forwardImagTempUrl = res
			return true
		}
		return false
	},

		/**
	 * 保存图片到本地相册
	 */
	onSaveImage(){
		var self = this
		if(self.currentOption == null){
			return
		}
		if(!self.forwardImagTempUrl){
			if(!this.saveCurrentImage()){
				return
			}
		}
		var path = this.forwardImagTempUrl
		wx.saveImageToPhotosAlbum({
			filePath: path,
			success() { 
				wx.showToast({
					title: '成功',
					icon: 'success',
					duration: 1000
				})
			},
			fail:function(e){
				console.log(e)
				wx.showToast({
					title: '失败!请授权给我',
					icon: 'none',
					duration: 3000
				})
			}
		  })
	},

	/**
	 * 预览图片按钮被点击
	 */
	onPreviewImage(){
		var self = this
		if(! this.data.backwardUrl){
			return
		}
		if(!this.forwardImagTempUrl){
			if(!this.saveCurrentImage()){
				return
			}
		}
		wx.previewImage({
			urls: [this.forwardImagTempUrl] // 需要预览的图片http链接列表
		})

		
	},


})

